'use strict';

const Controller = require('egg').Controller;
let rules = {
  title: {
    type: 'string',
    required: true,
    desc: '视频标题'
  },
  url: {
    type: 'string',
    required: true,
    desc: '视频地址'
  },
  video_id: {
    type: 'int',
    required: true,
    desc: '所属视频ID'
  },
  desc: {
    type: 'string',
    required: true,
    desc: '描述'
  },
}
class Video_detailController extends Controller {
  async save() {
    const { ctx } = this
    const user_id = ctx.authUser.id
    ctx.validate(rules)
    const { title, url, video_id, desc } = ctx.request.body
    const video = await ctx.model.Video.findOne({
      where: {
        id: video_id,
        user_id
      }
    })
    if (!video) {
      ctx.throw(404, '所属作品不存在')
    }
    const res = await ctx.model.VideoDetail.create({
      title, url, video_id, desc
    })
    ctx.apiSuccess(res)
  }

  async update() {
    const { ctx } = this
    const user_id = ctx.authUser.id
    const { id } = ctx.params
    ctx.validate({ id: { type: 'int', required: true, desc: '视频id' }, ...rules })
    const { title, url, video_id, desc } = ctx.request.body
    const video = await ctx.model.Video.findOne({
      where: {
        user_id,
        id: video_id
      }
    })
    if (!video) {
      ctx.throw(404, '所属作品不存在')
    }
    const vd = await ctx.model.VideoDetail.findOne({
      where: {
        id,
        video_id
      }
    })
    if (!vd) {
      ctx.throw(404, '当前记录不存在')
    }
    const res = await vd.update({ title, url, desc })
    ctx.apiSuccess(res)
  }

  async delete() {
    const { ctx } = this
    const user_id = ctx.authUser.id
    ctx.validate({
      id: { type: 'int', required: true, desc: '视频id' }
    })
    const { id } = ctx.params
    const vd = await ctx.model.VideoDetail.findOne({
      where: {
        id
      },
      include: [{
        model: ctx.model.Video,
        where: {
          user_id
        }
      }]
    })
    if (!vd) {
      ctx.throw(404, '该记录不存在')
    }
    await vd.destroy()
    ctx.apiSuccess('ok')
  }

  async index() {
    const { ctx } = this
    ctx.validate({ video_id: { type: 'int', required: true, desc: '视频id' } })
    const { video_id } = ctx.params
    const res = await ctx.model.VideoDetail.findAll({
      where: {
        video_id
      }
    })
    ctx.apiSuccess(res)
  }
}

module.exports = Video_detailController;
